package com.jiangfeixiang.springbootmybatis.config.dao;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * Created by jiangfeixiang on 2018/8/20
 */
@Configuration
public class SessionFactoryConfig {

    @Value("${mybatis.config-locations}")
    private String mybatisConfigFilePath;
    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;
    @Value("${mybatis.mapper-locations}")
    private String mapperPath;
    @Value("{mybatis.type-aliases-package}")
    private String entityPackage;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); // 创建SqlSession FactoryBean实例
        sqlSessionFactoryBean.setConfigLocation (new ClassPathResource ( mybatisConfigFilePath )); // 扫描mybatis配置文件;
        // 设置数据库连接信息
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 设置 mappe r映射器对应的XML文件的扫描路径
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+mapperPath;
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
        // 设置实体类扫描路径
        sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
        return sqlSessionFactoryBean;
    }
}
